﻿using Common.Model;
using System;
using System.Collections.Generic;
using Container.Library;
using Common.Library;
using Dapper.Library;
using Serialize.Library;
using DevOps.Model;

namespace DevOps.Logic
{
    /// <summary>
    /// 角色管理逻辑
    /// </summary>
    public class SysRoleServiceImpl : OperationLogicImpl, ISysRoleService
    {
        #region 角色基础信息管理操作

        #region 查询
        /// <summary>
        /// 根据条件分页查询角色数据
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<RoleInfoResponse>> LoadList(ParametersInfo<RoleInfoQuery> parameters)
        {
            var resultInfo = new ResultJsonInfo<List<RoleInfoResponse>>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SysRoleInfoEntity>().Where(a => a.is_deleted == false);
                if (parameters.parameters.sKeyWords.IsNotNullOrEmpty())
                {
                    result.Where(a => a.name.Contains(parameters.parameters.sKeyWords) || a.describe.Contains(parameters.parameters.sKeyWords));
                }

                #region 排序
                if (parameters.field.IsNullOrEmpty())
                {
                    parameters.field = " sort";
                }
                if (parameters.order.IsNullOrEmpty())
                {
                    parameters.order = " asc";
                }
                if (parameters.order.ToLower() == "asc")
                {
                    result.OrderBy(parameters.field);
                }
                else
                {
                    result.OrderByDescing(parameters.field);
                }
                #endregion

                var listInfo = result.PageList(parameters.page, parameters.limit);

                if (listInfo.Items.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo.Items.MapToList<RoleInfoResponse>();
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Data = new List<RoleInfoResponse>();
                    resultInfo.Msg = "无对应信息！";
                }
            }

            return resultInfo;
        }
        /// <summary>
        /// 查询单个角色的数据
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ResultJsonInfo<RoleInfoResponse> LoadSingle(string roleId)
        {
            var resultInfo = new ResultJsonInfo<RoleInfoResponse>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SysRoleInfoEntity>().Where(a => a.id == roleId).Get();
                if (result == null)
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "参数无效！";
                    return resultInfo;
                }
                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = result.MapTo<RoleInfoResponse>();
            }

            return resultInfo;

        }
        #endregion

        #region 添加
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="roleAdd"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AddRole(RoleInfoAddRequest roleAdd)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();

                var roleinfo = roleAdd.MapTo<SysRoleInfoEntity>();
                roleinfo.creator_id = user.id;
                roleinfo.creator_name = user.realname;
                roleinfo.modifier_date = DateTime.Now;
                roleinfo.modifier_id = user.id;
                roleinfo.modifier_name = user.realname;

                var roleInfo = con.QuerySet<SysRoleInfoEntity>().Where(p => p.name.Equals(roleAdd.name)&& p.is_deleted==false).Get();
                if (roleInfo==null)
                {
                    var result = con.CommandSet<SysRoleInfoEntity>().Insert(roleinfo);
                    if (result != 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "添加成功！";
                        AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.RoleManage, $"添加了一个新的角色，新增角色信息：{JsonHelper.ToJson(roleinfo)}");
                    }
                    else
                    {
                        resultInfo.Code = ActionCodes.InvalidOperation;
                        resultInfo.Msg = "添加失败";
                    }
                }
                else
                {
                    resultInfo.Code = ActionCodes.InvalidOperation;
                    resultInfo.Msg = "添加失败，请确保角色名唯一！";
                }
            }
            return resultInfo;
        }

        #endregion

        #region 修改

        /// <summary>
        /// 修改角色数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Modify(RoleInfoModifyRequest request)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();

                var roleinfo = con.QuerySet<SysRoleInfoEntity>().Where(a => a.id == request.id).Get();
                roleinfo.describe = request.describe;
                roleinfo.name = request.name;
                roleinfo.sort = request.sort;
                roleinfo.is_valid = request.is_valid;
                roleinfo.modifier_date = DateTime.Now;
                roleinfo.modifier_id = user.id;
                roleinfo.modifier_name = user.realname;

                var result = con.CommandSet<SysRoleInfoEntity>().Update(roleinfo);
                if (result > 0)
                {
                    //这里更改了角色信息，要把Redis中的关于用于可使用的菜单的信息清理掉
                    FunctionCfgServiceRedis.RemoveFunctionCfg();

                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "修改成功！";
                    AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.RoleManage, $"修改角色成功，修改角色信息：{JsonHelper.ToJson(roleinfo)}");
                }
                else
                {
                    resultInfo.Msg = "修改失败！";
                }
            }

            return resultInfo;
        }

        /// <summary>
        /// 禁用/启用角色
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ForbidOrEnable(string roleId)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();
                var roleinfo = con.QuerySet<SysRoleInfoEntity>().Where(a => a.id == roleId).Get();
                if (roleinfo == null)
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "参数无效！";
                    return resultInfo;
                }
                if (roleinfo.is_valid)
                {
                    roleinfo.is_valid = false;
                }
                else
                {
                    roleinfo.is_valid = true;
                }
                roleinfo.modifier_date = DateTime.Now;
                roleinfo.modifier_id = user.id;
                roleinfo.modifier_name = user.realname;

                var result = con.CommandSet<SysRoleInfoEntity>().Update(roleinfo);
                if (result > 0)
                {
                    //这里更改了角色信息，要把Redis中的关于用于可使用的菜单的信息清理掉
                    FunctionCfgServiceRedis.RemoveFunctionCfg();

                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "禁用/启用角色成功！";
                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.RoleManage, $"禁用/启用角色成功，禁用/启用角色信息：{JsonHelper.ToJson(roleId)}");
                }
                else
                {
                    resultInfo.Msg = "禁用/启用角色失败！";
                }
            }
            return resultInfo;

        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> roleIds)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();
                //事务功能
                con.Transaction(tran =>
                {
                    var ids = roleIds.ToArray();
                    var roleinfo = tran.QuerySet<SysRoleInfoEntity>().Where(a => a.id.In(ids)).ToList();
                    //判断传入的ids是否都有效
                    if (roleinfo.Count == roleIds.Count)
                    {
                        //判断是否被用户或部门使用。如果被使用了，就不能被删除，只能被停用
                        var groupRoleReInfo = tran.QuerySet<SysRolePermissionReEntity>().Where(a => a.role_id.In(ids)).Count();
                        if (groupRoleReInfo == 0)
                        {
                            //判断是否被用户使用。如果被使用了，就不能被删除，只能被停用
                            var userRoleReInfo = tran.QuerySet<SysUserRoleReEntity>().Where(a => a.role_id.In(ids)).Count();
                            if (userRoleReInfo == 0)
                            {
                                var result = 0;
                                foreach (var item in roleinfo)
                                {
                                    item.is_deleted = true;
                                    item.modifier_date = DateTime.Now;
                                    item.modifier_id = user.id;
                                    item.modifier_name = user.realname;
                                    result = tran.CommandSet<SysRoleInfoEntity>().Update(item);
                                }

                                //删除权限与角色之间的关联
                                var deleteroleper = tran.CommandSet<SysRolePermissionReEntity>().Where(a => a.role_id.In(ids)).Delete();
                                if (result > 0)
                                {
                                    //这里更改了角色信息，要把Redis中的关于用于可使用的菜单的信息清理掉
                                    FunctionCfgServiceRedis.RemoveFunctionCfg();

                                    resultInfo.Code = ActionCodes.Success;
                                    resultInfo.Msg = "删除成功！";
                                    AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.RoleManage, $"删除角色成功，删除角色信息：{JsonHelper.ToJson(roleIds)}");
                                }
                                else
                                {
                                    resultInfo.Msg = "删除失败！";
                                }
                            }
                            else
                            {
                                resultInfo.Msg = "选中角色，已被用户使用，无法删除！";
                            }
                        }
                        else
                        {
                            resultInfo.Msg = "选中角色，已被用户组使用，无法删除！";
                        }
                    }
                    else
                    {
                        resultInfo.Code = ActionCodes.ArgumentInvalid;
                        resultInfo.Msg = "参数无效！";
                    }
                }, ex =>
                {
                    throw ex;
                });
            }
            return resultInfo;
        }

        #endregion

        #endregion

        #region 权限相关操作
        /// <summary>
        /// 获取所有角色Select数据
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SelectListInfo>> LoadAllSelectList()
        {

            var resultInfo = new ResultJsonInfo<List<SelectListInfo>>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SysRoleInfoEntity>().Where(a => a.is_deleted == false && a.is_valid == true).ToList();

                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = result.MapToList<SelectListInfo>();

            }
            return resultInfo;
        }
        #endregion

        #region 批量导入导出操作
        /// <summary>
        /// 事务批量导入角色信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> TranBulkImportRole(List<RoleInfoAddRequest> selects)
        {

            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    
                    for (int i = 0; i < selects.Count; i++)
                    {
                        selects[i].is_valid = selects[i].ifis_valid == "已启用" ? true : false;
                    }
                    var roles = selects.MapToList<SysRoleInfoEntity>();
                    var result = tran.CommandSet<SysRoleInfoEntity>().Insert(roles);

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "导入成功！";
                        AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.RoleManage, $"事务导入角色成功，导入角色信息：{JsonHelper.ToJson(selects)}");
                    }

                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 非事务批量导入角色信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> BulkImportRole(List<RoleInfoAddRequest> selects)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                for (int i = 0; i < selects.Count; i++)
                {
                    selects[i].is_valid = selects[i].ifis_valid == "已启用" ? true : false;
                }
                var roles = selects.MapToList<SysRoleInfoEntity>();
                var result = 0;
                for (int i = 0; i < roles.Count; i++)
                {
                    try
                    {
                        result += con.CommandSet<SysRoleInfoEntity>().Insert(roles[i]);
                    }
                    catch
                    {
                        resultInfo.Msg = resultInfo.Msg + "第" + (i + 1) + "条数据添加失败！";
                    }
                }

                if (result == roles.Count)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "导入成功！";
                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.RoleManage, $"非事务导入角色成功，导入角色信息：{JsonHelper.ToJson(selects)}");
                }
                else if (result == 0)
                {
                    resultInfo.Code = ActionCodes.InvalidOperation;
                    resultInfo.Msg = "导入失败！";

                }
                else
                {
                    resultInfo.Code = ActionCodes.Success;

                }

            }
            return resultInfo;
        }
        /// <summary>
        /// 批量导出所有
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<RoleInfoResponse>> ListAll()
        {
            var resultInfo = new ResultJsonInfo<List<RoleInfoResponse>>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SysRoleInfoEntity>().Where(a => a.is_deleted == false).ToList();

                if (result.Count > 0)
                {
                    var outuser = result.MapToList<RoleInfoResponse>();
                    outuser.ForEach(a => a.ifis_valid = a.is_valid ? "已启用" : "未启用");

                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = outuser;
                }
                else
                {
                    resultInfo.Data = new List<RoleInfoResponse>();
                    resultInfo.Msg = "无对应信息！";
                }
            }

            return resultInfo;
        }

        #endregion
    }
}
